package net.sunzc.hwfacetest.utils;

import android.graphics.*;
import android.text.TextUtils;
import android.util.Base64;

import java.io.*;

public class ReadFromFile {

    private static String saveFile(String path, String name, String data) {
        try {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(path + name);
            fos.write(data.getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void readTxtFile(String filePath) {
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                String aaString = "";
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    aaString = aaString + lineTxt;
                }
                String aa = aaString;
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }

    }

    /**
     * 将文件读取为16进制String
     * Read original File and transfer it into Hex String
     *
     * @return
     * @throws IOException
     */
    public static String readOriginal2Hex(String filePath) {

        StringWriter sw = new StringWriter();
        try {
            FileInputStream fin = new FileInputStream(new File(filePath));
            int len = 1;
            byte[] temp = new byte[len];

	       /*16进制转化模块*/
            for (; (fin.read(temp, 0, len)) != -1; ) {
                if (temp[0] > 0xf && temp[0] <= 0xff) {
                    sw.write(Integer.toHexString(temp[0]));
                } else if (temp[0] >= 0x0 && temp[0] <= 0xf) {//对于只有1位的16进制数前边补“0”
                    sw.write("0" + Integer.toHexString(temp[0]));
                } else { //对于int<0的位转化为16进制的特殊处理，因为Java没有Unsigned int，所以这个int可能为负数
                    sw.write(Integer.toHexString(temp[0]).substring(6));
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return sw.toString();
    }

    /**
     * 将替换后的16进制字符串写回文件
     * write replaced original String to file
     *
     * @param replaced
     * @throws NumberFormatException
     * @throws IOException
     */
    public static void writeNew2Binary(String replaced, String filePath) {
        try {
            File file = new File(filePath);
            File dir = file.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fout = new FileOutputStream(file);
            for (int i = 0; i < replaced.length(); i = i + 2) {
                fout.write(Integer.parseInt(replaced.substring(i, i + 2), 16));
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    public static String xhFilePath(String path) {
        File dir = new File(path);
        File[] listFiles = dir.listFiles();
        if (listFiles == null) return "";
        for (File file : listFiles) {
            if (file.isFile()) {
                File filechild = new File(file.getPath());
                String filename = filechild.getName();
                if ("2.jpg".equals(filename)) {
                    String pathQ = filechild.getAbsolutePath();
                    Bitmap Bitmap2Bytes = BitmapFactory.decodeFile(pathQ);
                    String base64Str = xhFilePath(Bitmap2Bytes);
                    FileUtils.delFile(dir);
                    return base64Str;
                }
            } else if (file.isDirectory()) { // 读取文件夹下面文件
                String str = xhFilePath(file.getPath());
                if (!TextUtils.isEmpty(str)) {
                    return str;
                }
            }
        }
        return "";
    }

    public static Bitmap addTextToBitmap(Bitmap srcBitmap, String timeStr) {
        int w = srcBitmap.getWidth();
        int h = srcBitmap.getHeight();
        Bitmap timeBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(timeBitmap);
        Paint p = new Paint();
        Typeface font = Typeface.create("宋体", Typeface.BOLD);
        p.setColor(Color.RED);
        p.setTypeface(font);
        p.setTextSize(18);
        canvas.drawBitmap(srcBitmap, 0, 0, p);
        canvas.drawText(timeStr, 10, 30, p);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return timeBitmap;
    }

    public static String xhFilePath(Bitmap bitmap) {
        if (bitmap != null) {
            bitmap = addTextToBitmap(bitmap, DateUtils.getCurrentDateTime());
            return Base64.encodeToString(bitmap2Bytes(bitmap), Base64.DEFAULT);
        }
        return "";
    }

    public static byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }
}
